﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using CommunityServerRest;
using System.Windows.Forms;
using CSWriter.Properties;
using System.IO;
using System.Net;

namespace CSWriter.Blogs {
	public class BlogManager {

		BlogService service;

		public BlogManager(BlogService service) {
			this.service = service;
		}

		public void DeletePost(BlogPost p) {
			service.Delete(p.Id);
		}

		/// <summary>
		/// Devuelve un artículo editable, con adjunto incluído si se da el caso
		/// </summary>
		public BlogPostItem GetBlogPostItem(BlogPost post) {
			return GetBlogPostItem(post.Id);
		}
		public BlogPostItem GetBlogPostItem(int id) {
			BlogPost post=service.GetPost(id);
			BlogPostItem postItem = new BlogPostItem(post);

			if (post.AttachmentInfo != null) {
				postItem.Attachment = service.GetAttachment(post.Id);
			}

			return postItem;
		}

		private void OnPostDeleted(BlogPost p) {
			if (PostDeleted != null)
				PostDeleted(this, new BlogPostEventArgs(p));
		}

		public delegate void PostEventHandler(object sender, BlogPostEventArgs e);
		public event PostEventHandler PostDeleted;


		public BlogPostList GetRecentPosts(int p) {
			return service.GetRecentPosts(p);
		}

		internal BlogList GetBlogs() {
			return service.Blogs();
		}

		internal BlogPost CreatePost(BlogPostItem post) {

			bool creado = false;
			int t = 0;	//Número de intentos de envío
			BlogPost ret=null;
			do {
				try {
					ret = service.CreatePost(post.ToRestPost(), post.BlogInfo.Id);
					creado = true;

				} catch (WebException ex) {
					if (t < 3) {
						post.Name = NombreAlternativo(post.Title);
					} else {
						throw ex;
					}
					t++;
				}
			} while (!creado);


			if (post.Attachment != null) {
				//Adjunta el archivo 
				if (post.Attachment != null) {
					service.CreateAttachment(post.Attachment, ret.Id);
				}
			}
			return ret;
		}

		private string NombreAlternativo(string p) {
			return string.Concat(p, Guid.NewGuid().ToString());
		}
		internal void UpdatePost(BlogPostItem post) {
			service.UpdatePost(post.ToRestPost());
			if (PublishedVersionHasAttachment(post)) {
				if (post.Attachment != null)
					service.UpdateAttachment(post.Attachment, post.Id);
				else
					service.DeleteAttachment(post.Id);
			} else if (post.Attachment!=null) {
				service.CreateAttachment(post.Attachment, post.Id);
			}
		}

		private bool PublishedVersionHasAttachment(BlogPostItem Post) {
			return !((service.GetPost(Post.Id)).AttachmentInfo == null);
		}


		internal Blog GetBlog(int p) {
			return service.GetBlog(p);
		}
	}

	public class BlogPostEventArgs : EventArgs {
		public BlogPostEventArgs(BlogPost post) {
			Post = post;
		}
		public BlogPost Post { get; private set; }
	}
}
